package com.cx.io;

import java.io.*;

public class SerializationExample {
    public static void main(String[] args) {
        // 序列化
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"))) {
            // 创建一个Person对象
            Person person = new Person("Alice", 30);
            // 将Person对象写入文件
            oos.writeObject(person);
        } catch (IOException e) {
            // 打印异常信息
            e.printStackTrace();
        }

        // 反序列化
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {
            // 从文件中读取Person对象
            Person person = (Person) ois.readObject();
            // 打印Person对象的属性
            System.out.println(person.getName() + ", " + person.getAge());
        } catch (IOException | ClassNotFoundException e) {
            // 打印异常信息
            e.printStackTrace();
        }
    }
}

class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}